import threading
from tkinter import ttk, simpledialog  # 导入 simpledialog 用于创建输入对话框
import tkinter as tk
from tkinter import messagebox

from pk.WindowManager import WindowManager


class Zhuagui:
    def __init__(self, setupui):
        self.setupUi = setupui
        self.threads = []  # 用于存储所有挖图线程
        self.stop_flag = threading.Event()

    def btn_command(self):
            if any(thread.is_alive() for thread in self.threads):
                self.stop_flag.set()
                for thread in self.threads:
                    thread.join(timeout=1)  # 增加超时时间
                self.threads = []  # 清空线程列表
                self.setupUi.btn_zg.config(text="自动抓鬼")
                self.setupUi.add_log("停止自动抓鬼")
            else:
                self.setupUi.add_log("开始自动抓鬼")
                if self.setupUi.selectHwnd:
                    self.setupUi.add_log("开始自动抓鬼")
                    # 弹出输入框让用户输入抓鬼次数
                    times = simpledialog.askinteger("输入抓鬼次数", "请输入抓鬼次数（最少为1）",
                                                    parent=self.setupUi.root,
                                                    minvalue=1)
                    if times is None:
                        return  # 用户取消输入
                    if times < 1:
                        tk.messagebox.showerror("错误", "抓鬼次数最少为1，请重新输入！")
                        return

                    self.stop_flag.clear()
                    # self.threads = []  # 清空线程列表
                    for hwnd in self.setupUi.selectHwnd:
                        thread = threading.Thread(target=self.run_command, args=(hwnd, times,))
                        thread.daemon = True
                        thread.start()
                        self.threads.append(thread)
                    self.setupUi.btn_zg.config(text="停止抓鬼")
                    self.setupUi.add_log(f"开始自动抓鬼，抓鬼次数: {times}")
                else:
                    self.setupUi.add_log("未选择窗口，无法开始自动抓鬼")
                    return
    def run_command(self, hwnd, times):
        try:
            for x in range(times):
                if self.stop_flag.is_set():
                    break
                self.setupUi.add_log(f"第 {x + 1} 次抓鬼开始")
                WindowManager.sleep(0.3)

                while not self.stop_flag.is_set():
                    WindowManager.sleep(0.1)
                    f = WindowManager.findImgAndClick(hwnd, "image/zhuagui/zhuaguirenwu.png")
                    if f:
                        break

                while not self.stop_flag.is_set():
                    WindowManager.sleep(0.3)
                    f = WindowManager.findImgAndDubleClick(hwnd, "image/zhuagui/zc-zg.png")
                    if f:
                        break

                # 拆分长时间休眠，增加状态检查
                total_sleep_time = 500
                while total_sleep_time > 0 and not self.stop_flag.is_set():
                    WindowManager.sleep(0.6)
                    total_sleep_time -= 1

                while not self.stop_flag.is_set():
                    WindowManager.sleep(2)
                    f = WindowManager.findImg(hwnd, "image/zhuagui/zhuaguiwancheng.png")
                    if f:
                        break

                while not self.stop_flag.is_set():
                    WindowManager.sleep(0.3)
                    f = WindowManager.findImgAndClick(hwnd, "image/zhuagui/queren.png")
                    if f:
                        break

                self.setupUi.add_log(f"第 {x + 1} 次抓鬼结束")
        except Exception as e:
            print(f"抓鬼线程出错: {e}")
